package dat03;
import java.io.RandomAccessFile;
import java.util.Scanner;

public class Test06 {
    /**
     * 要求用户输入一个当前目录下的文件名，完成复制该文件内容，新文件取名为"原文件名_copy.后缀名"
     * 定义两个方法分别使用单字节形式复制，以及字节数组形式复制 - 使用RandomAccessFile
     * @author Admin
     *
     */
    public static void main(String[] args) {
           copy1();
           copy2();
    }
//    单子节形式复制
    public static void copy1(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件名");
        String s = sc.nextLine().trim();
        try {
            RandomAccessFile raf = new RandomAccessFile("src/dat03/"+s,"r");
           String src = s.substring(0,s.indexOf("."));
           String src1 = s.substring(s.indexOf("."));
           RandomAccessFile raf1 = new RandomAccessFile("src/dat03/"+src+"_copy"+src1,"rw");
           int len =0;
           while ((len=raf.read())!= -1){
               raf1.write(len);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //字节数组形式复制
    public static void copy2(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件名");
        String s = sc.nextLine().trim();
        try {
            RandomAccessFile raf = new RandomAccessFile("src/dat03/"+s,"r");
            String src = s.substring(0,s.indexOf("."));
            String src1 = s.substring(s.indexOf("."));
            RandomAccessFile raf1 = new RandomAccessFile("src/dat03/"+src+"_copy"+src1,"rw");
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = raf.read(buffer)) != -1) {
                raf1.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}